package admin

import (
	"duoke/internal/dao"
	"duoke/model"
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/request"
	"duoke/utils/response"
	"duoke/utils/valid"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/grand"
)

var User = new(userCtl)

type userCtl struct{}

func (ctl *userCtl) All(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	list, total, err := service.User.Page(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", gin.H{"total": total, "list": list})
}

func (ctl *userCtl) List(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	list, total, err := service.SeparateGroup.Page(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", gin.H{"total": total, "list": list})
}
func (ctl *userCtl) Save(c *gin.Context) {
	var req model.ReqGoodsUser
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	// 保存数据
	err := service.User.Save(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "保存成功", nil)
}
func (ctl *userCtl) Set(c *gin.Context) {
	req := request.JsonMap(c)
	userId := req["id"]
	if userId == nil || userId == "" {
		response.Error(c, "请选择用户", nil)
		return
	}
	isSuccess, err := service.GoodsUser.Set(gconv.Int(userId), gconv.String(req["type"]))
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !isSuccess {
		response.Error(c, "设置失败", nil)
		return
	}
	response.Success(c, "设置成功", nil)
}

func (ctl *userCtl) Del(c *gin.Context) {
	var req model.ReqId
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	err := service.GoodsUser.Del(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "删除成功", nil)
}
func (ctl *userCtl) Tixian(c *gin.Context) {
	req := request.JsonMap(c)
	userId := req["user_id"]
	if userId == nil || userId == "" {
		response.Error(c, "请选择用户", nil)
		return
	}
	userRecord, err := dao.User.Ctx(c).Where("id", userId).One()
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	user := userRecord.Map()
	if gconv.Int(user["id"]) == 0 {
		response.Error(c, "用户不存在", nil)
		return
	}
	txAmount := gconv.Float64(user["money"])
	if txAmount <= 0 {
		response.Error(c, "用户余额不足，不可体现", nil)
		return
	}
	OrderNo := gtime.Now().Format("YmdHis") + "cash" + gconv.String(grand.Intn(99))
	isSuccess, err := service.WechatPay.RefundV3(c, txAmount, OrderNo, txAmount)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if isSuccess {
		// 余额清零
		result, err := dao.User.Ctx(c).Where("id", gconv.Int(user["id"])).Unscoped().Decrement("money", txAmount)
		if err != nil {
			response.Error(c, err.Error(), nil)
			return
		}
		if rowsCount, err := result.RowsAffected(); err != nil || rowsCount == 0 {
			response.Error(c, "提现失败", nil)
			return
		}
		// 新增余额记录
		result, err = dao.UserMoneyLog.Ctx(c).Data(g.Map{
			"user_id":    gconv.Int(user["id"]),
			"amount":     -txAmount,
			"status":     1,
			"pay_time":   gtime.Timestamp(),
			"created_at": gtime.Timestamp(),
		}).Unscoped().Insert()
		if rowsCount, err := result.RowsAffected(); err != nil || rowsCount == 0 {
			response.Error(c, "余额记录新增失败", nil)
			return
		}
		response.Success(c, "退款成功", nil)
		return
	} else {
		response.Error(c, "退款失败", nil)
		return
	}
}
func (ctl *userCtl) RechargeBalance(c *gin.Context) {
	req := request.JsonMap(c)
	userId := gconv.Int(req["user_id"])
	money := gconv.Float64(req["money"])
	if userId == 0 || money == 0 {
		response.Error(c, "参数缺失【money/user_id】", nil)
		return
	}
	var remark string
	if money > 0 {
		remark = "后台充值余额"
	} else {
		remark = "后台扣除余额"
	}
	err := service.User.Money(c, userId, money, remark, "user_recharge")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "充值成功", nil)
	return
}
func (ctl *userCtl) WithdrawalList(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	list, err := service.User.WithdrawalList(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", list)
}
func (ctl *userCtl) WithdrawalSave(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	state := gconv.Int(req["state"])
	reason := gconv.String(req["reason"])
	if id == 0 || state == 0 {
		response.Error(c, "参数缺失【id/state】", nil)
		return
	}
	err := service.User.WithdrawalSave(c, id, state, reason)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "修改成功", nil)
}
